package com.ts.enterprise.common.service.impl;

import com.ts.enterprise.common.consts.SmsConstants;
import com.ts.enterprise.common.utils.RedisUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.ts.enterprise.common.service.SmsManagerService;
import com.ts.enterprise.common.utils.SmsManagerBuilder;
import com.ts.enterprise.enums.RedisKeyEnum;
import com.ts.enterprise.exception.BusinessException;
import com.ts.enterprise.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 短信验证码表 服务实现类
 * </p>
 *
 * @author Dean
 * @since 2019-09-18
 */
@Service
@Slf4j
public class SmsManagerServiceImpl implements SmsManagerService {

    @Autowired
    private SmsManagerBuilder smsManager;

    @Override
    public boolean sendSmsCode(String mobile, String smsCode) {
        Map<String, String> param = new HashMap<>();
        param.put("code", smsCode);
        boolean b = smsManager.sendAckStatus(mobile, SmsConstants.SIGN_NAME, SmsConstants.TEMPLATE_SMS_240825796, param);
        if (b) {
            RedisUtil.set(RedisKeyEnum.getRedisKey(RedisKeyEnum.SMS_CODE, mobile), smsCode, RedisKeyEnum.SMS_CODE.getExpiredTime());
            return true;
        }
        throw new BusinessException(ExceptionEnum.SMS_SEND_FAIL);
    }

    @Override
    public boolean checkSmsCode(String mobile, String smsCode) {
        String smsKey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMS_CODE, mobile);
        if (smsCode.equals(RedisUtil.get(smsKey))){
            RedisUtil.del(smsKey);
            return true;
        }
        throw new BusinessException(ExceptionEnum.VERIFICATION_CODE_EXCEPTION);
    }


}
